package com.ys.service.hr.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.hr.ThrUserArchives;
import com.ys.entity.hr.ThrUserArchivesRecord;
import com.ys.entity.sys.TsOrganizationInfo;
import com.ys.entity.sys.TsUserInfo;
import com.ys.entity.sys.YsCol;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.ThrUserArchivesMapper;
import com.ys.mapper.hr.ThrUserArchivesRecordMapper;
import com.ys.service.hr.ThrUserArchivesService;
import com.ys.service.sys.TsUserInfoService;
import com.ys.util.CheckUtil;
import com.ys.util.DateUtil;
import com.ys.util.RedisUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Predicate;

@Service("thrUserArchivesService")
public class ThrUserArchivesServiceImpl implements ThrUserArchivesService {
	private static final Logger logger = LoggerFactory.getLogger(ThrUserArchivesServiceImpl.class);

	@Autowired
	private ThrUserArchivesMapper thrUserArchivesMapper;

	@Autowired
	private ThrUserArchivesRecordMapper thrUserArchivesRecordMapper;

	@Autowired
	private TsUserInfoService tsUserInfoService;

	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private HrMapper hrMapper;

	@Autowired
	private RedisUtil redisUtil;

	/**
	 * 新增
	 */
	@Override
	public ThrUserArchives add(Map<String, Object> params) throws Exception{
		ThrUserArchives thrUserArchives = JSON.parseObject(JSON.toJSONString(params), ThrUserArchives.class);
		thrUserArchives.setStatus(1);

		int result = thrUserArchivesMapper.insert(thrUserArchives);

		return thrUserArchives;
	}

	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params,Long menuId) throws Exception{
		logger.info("人员档案修改传参："+params);

		//去除多余参数，只保留有权限编辑的参数
		//去除编辑只读的字段
		Map<String, Object> paramsNew = removeSurplusParams(params,menuId,true,item->item.getFormEditReadonly()!=null && item.getFormEditReadonly()==1);
		//参数验证
		String errorMsg = checkParams(paramsNew,menuId,"THR_UserArchives",ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1 && ysColItem.getFormEditReadonly()!=1);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		//验证详情信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				if(jSONObject.get("id")!=null)paramsNewByRecord.put("id",jSONObject.get("id"));//id
				if(jSONObject.get("userId")!=null)paramsNewByRecord.put("userId",jSONObject.get("userId"));//工号
				if(jSONObject.get("recordTime")!=null)paramsNewByRecord.put("recordTime",jSONObject.get("recordTime"));//记录时间
				if(jSONObject.get("recordType")!=null)paramsNewByRecord.put("recordType",jSONObject.get("recordType"));//属性（0奖励、1过错）
				if(jSONObject.get("remark")!=null)paramsNewByRecord.put("remark",jSONObject.get("remark"));//描述
				paramsNewByItem.add(paramsNewByRecord);
			}
		}else {
			//return R.error("详情信息为空！");
		}
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		//保存头部信息
		ThrUserArchives thrUserArchives = JSON.parseObject(JSON.toJSONString(paramsNew), ThrUserArchives.class);
		thrUserArchives.setStatus(1);
		if(checkUtil.isNotNullByObject(paramsNew.get("id"))){//修改
			thrUserArchivesMapper.update(thrUserArchives);
			hrMapper.updateUserNameByUserId(thrUserArchives.getUserId(),thrUserArchives.getUserName());
		}
		if(paramsNewByItem!=null && paramsNewByItem.size()>0){
			//保存详情信息
			hrMapper.deleteUserArchivesRecorByUserId(thrUserArchives.getUserId());
			for(Map<String, Object> itemMap: paramsNewByItem){
				ThrUserArchivesRecord thrUserArchivesRecord = JSON.parseObject(JSON.toJSONString(itemMap), ThrUserArchivesRecord.class);

				thrUserArchivesRecordMapper.insert(thrUserArchivesRecord);
				/*
				if(checkUtil.isNotNullByObject(thrUserArchivesRecord.getId())){//修改
					thrUserArchivesRecordMapper.update(thrUserArchivesRecord);
				}else {//新增
					thrUserArchivesRecordMapper.insert(thrUserArchivesRecord);
				}

				 */
			}
		}
		//同步用户信息表信息
		if(params.get("userLeader")!=null)params.put("headUserId",params.get("userLeader").toString());
		if(params.get("userLeaderName")!=null)params.put("headUserId",params.get("headUserName").toString());
		if(params.get("belongCompany")!=null)params.put("cid",params.get("belongCompany").toString());
		if(params.get("belongCompanyName")!=null)params.put("cidName",params.get("belongCompanyName").toString());
		if(params.get("deptId")!=null){
			TsOrganizationInfo tsOrganizationInfo = new TsOrganizationInfo().setOrgid(params.get("deptId").toString()).queryFirst();
			if(tsOrganizationInfo!=null){
				params.put("orgId",tsOrganizationInfo.getId());
				if(tsOrganizationInfo.getOrgPathAll()!=null)params.put("deptPath",tsOrganizationInfo.getOrgPathAll());
				if(tsOrganizationInfo.getOrgPathNameAll()!=null)params.put("deptPathName",tsOrganizationInfo.getOrgPathNameAll());
			}
		}
		TsUserInfo tsUserInfo = new TsUserInfo().setUserId(params.get("userId").toString()).queryFirst();
		params.put("id",tsUserInfo.getId());
		if(params.get("userState")!=null){
			if(Integer.parseInt(params.get("userState").toString())==3){//离职
				params.put("status",0);
			}else {
				params.put("status",1);
			}
			try {
				String userState = "在职";
				int disabled = 0;
				int status = 1;
				if(Integer.parseInt(params.get("userState").toString())==3) {//离职
					userState = "离职";
					disabled = 1;
					status = 0;
				}
				hrMapper.updateUserStatusByOld(params.get("userId").toString(),disabled,userState,status);
			}catch (Exception e){
				logger.info("TS_UserInfo表字段被删除");
			}
		}
		tsUserInfoService.edit(params);
		return R.ok(AddDto.gotoEdit("/web/hr/thrUserArchives/toEdit?id=" + thrUserArchives.getId()));
	}



	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId, String tableName, Predicate<YsCol> notNullCondition) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType(tableName,listField,params,notNullCondition);
		if(checkUtil.isNotNullByObject(params.get("idCard")) && !checkUtil.isIDNumberValid(params.get("idCard").toString())){
			backMsg = "身份证号格式有误！";
		}
		return backMsg;
	}


	/**
	 * 去除多余参数，只保留有权限编辑的参数
	 */
	public Map<String, Object> removeSurplusParams(Map<String, Object> params,Long menuId,boolean hasSonList, Predicate<YsCol> notNullCondition) throws Exception {
		Map<String, Object> paramsNew = new HashMap<>();
		//获取pc编辑只读字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.queryList();
		paramsNew.put("id",params.get("id")!=null?params.get("id"):"");//id必需
		if(hasSonList){//如果有权限修改子表信息，则保留
			paramsNew.put("subData",params.get("subData"));
		}
		if(listField!=null && listField.size()>0){
			for (String key : params.keySet()) {
				boolean isReadOnly = false;//是否只读
				for (YsCol item : listField) {
					//item.getFormEditReadonly()!=null && item.getFormEditReadonly()==1
					if(item.getCode().equals(key)  && notNullCondition.test(item)){
						isReadOnly = true;
					}
				}
				if(!isReadOnly){//如果非只读，即是有权限修改的
					paramsNew.put(key,params.get(key));
				}
			}
		}
		return paramsNew;
	}




	/**
	 * 来自用户信息表的新增同步
	 */
	@Override
	public void addFromUserInfo(Map<String, Object> params){
		try {
			int num = 0;
			//设置档案编码（格式：YGDA年月日三位序号）
			if(redisUtil.get("thrUserArchivesBid")!= null && !"".equals(redisUtil.get("ThrUserArchivesBid"))){
				num = Integer.parseInt(redisUtil.get("thrUserArchivesBid"))+1;
			}
			//设置档案编码（格式：YGDA年月日三位序号）
			String archivesBid = "YGDA"+ DateUtil.getYYYYMMDD(new Date())+String.format("%0"+3+"d", num);

			ThrUserArchives thrUserArchives = new ThrUserArchives();
			thrUserArchives.setArchivesBid(archivesBid);//档案编码
			thrUserArchives.setUserId(params.get("userId").toString());//用户工号
			if(checkUtil.isNotNullByObject(params.get("userName")))thrUserArchives.setUserName(params.get("userName").toString());//用户名字
			if(checkUtil.isNotNullByObject(params.get("userSex")))thrUserArchives.setUserSex(Integer.parseInt(params.get("userSex").toString()));//用户性别
			if(checkUtil.isNotNullByObject(params.get("nativePlace")))thrUserArchives.setNativePlace(params.get("nativePlace").toString());//用户籍贯
			if(checkUtil.isNotNullByObject(params.get("workCity")))thrUserArchives.setWorkCity(params.get("workCity").toString());//工作城市
			if(checkUtil.isNotNullByObject(params.get("officeId")))thrUserArchives.setOfficeId(Long.parseLong(params.get("officeId").toString()));//所属办公室Id
			if(checkUtil.isNotNullByObject(params.get("roleId")))thrUserArchives.setRoleId(Long.parseLong(params.get("roleId").toString()));//角色Id
			if(checkUtil.isNotNullByObject(params.get("roleIdAttribute")))thrUserArchives.setRoleIdAttribute(Integer.parseInt(params.get("roleIdAttribute").toString()));//角色属性
			if(checkUtil.isNotNullByObject(params.get("userLeader")))thrUserArchives.setHeadUserId(params.get("userLeader").toString());//用户上级工号
			if(checkUtil.isNotNullByObject(params.get("deptId")))thrUserArchives.setDeptId(params.get("deptId").toString());//所属部门编号
			if(checkUtil.isNotNullByObject(params.get("cid")))thrUserArchives.setBelongCompany(params.get("cid").toString());//所属公司编码
			if(checkUtil.isNotNullByObject(params.get("userState")))thrUserArchives.setUserState(Integer.parseInt(params.get("userState").toString()));//员工状态（0实习、1试用、2正式、3离职）
			thrUserArchives.setStatus(1);
			if(params.get("userState")!=null){
				try {
					String userState = "在职";
					int disabled = 0;
					int status = 1;
					if(Integer.parseInt(params.get("userState").toString())==3) {//离职
						userState = "离职";
						disabled = 1;
						status = 0;
					}
					hrMapper.updateUserStatusByOld(params.get("userId").toString(),disabled,userState,status);
				}catch (Exception e){
					logger.info("TS_UserInfo表字段被删除");
				}
			}

			thrUserArchivesMapper.insert(thrUserArchives);
		} catch (Exception e){
			logger.error("出错：",e.getMessage(),e);
		}
	}



	/**
	 * 来自用户信息表的修改同步
	 */
	@Override
	public void updateFromUserInfo(Map<String, Object> params){
		try {
			logger.info("人员档案修改同步传参："+params);
			ThrUserArchives thrUserArchives = new ThrUserArchives().setUserId(params.get("userId").toString()).queryFirst();
			if(checkUtil.isNotNullByObject(params.get("userName")))thrUserArchives.setUserName(params.get("userName").toString());//用户名字
			if(checkUtil.isNotNullByObject(params.get("userSex")))thrUserArchives.setUserSex(Integer.parseInt(params.get("userSex").toString()));//用户性别
			if(checkUtil.isNotNullByObject(params.get("nativePlace")))thrUserArchives.setNativePlace(params.get("nativePlace").toString());//用户籍贯
			if(checkUtil.isNotNullByObject(params.get("workCity")))thrUserArchives.setWorkCity(params.get("workCity").toString());//工作城市
			if(checkUtil.isNotNullByObject(params.get("officeId")))thrUserArchives.setOfficeId(Long.parseLong(params.get("officeId").toString()));//所属办公室Id
			if(checkUtil.isNotNullByObject(params.get("roleId")))thrUserArchives.setRoleId(Long.parseLong(params.get("roleId").toString()));//角色Id
			if(checkUtil.isNotNullByObject(params.get("roleIdAttribute")))thrUserArchives.setRoleIdAttribute(Integer.parseInt(params.get("roleIdAttribute").toString()));//角色属性
			if(checkUtil.isNotNullByObject(params.get("userLeader")))thrUserArchives.setHeadUserId(params.get("userLeader").toString());//用户上级工号
			if(checkUtil.isNotNullByObject(params.get("deptId")))thrUserArchives.setDeptId(params.get("deptId").toString());//所属部门编号
			if(checkUtil.isNotNullByObject(params.get("cid")))thrUserArchives.setBelongCompany(params.get("cid").toString());//所属公司编码
			if(checkUtil.isNotNullByObject(params.get("userState")))thrUserArchives.setUserState(Integer.parseInt(params.get("userState").toString()));//员工状态（0实习、1试用、2正式、3离职）
			if(checkUtil.isNotNullByObject(params.get("userState"))){
				try {
					String userState = "在职";
					int disabled = 0;
					int status = 1;
					if(Integer.parseInt(params.get("userState").toString())==3) {//离职
						userState = "离职";
						disabled = 1;
						status = 0;
					}
					hrMapper.updateUserStatusByOld(params.get("userId").toString(),disabled,userState,status);
				}catch (Exception e){
					logger.info("TS_UserInfo表字段被删除");
				}
			}

			thrUserArchivesMapper.update(thrUserArchives);
		} catch (Exception e){
			logger.error("出错：",e.getMessage(),e);
		}
	}






}
